package com.example.systemserver.config;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.ResultBean;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setContentType("application/json;charset=utf-8");
        HttpServletRequest request = (HttpServletRequest) servletRequest;


        //对于一些特殊的请求， 应该直接放行
        String requestURI = request.getRequestURI(); // /file/images/xxxxx.jpg
        if (requestURI.equals("/account/login")||requestURI.startsWith("/file/download/")){
            filterChain.doFilter(servletRequest,servletResponse); //放行
            return;
        }


        String token = request.getHeader("token");
        try{
            JWTUtil.verify(token, "123456".getBytes()); //校验token
            filterChain.doFilter(servletRequest,servletResponse); //放行
        }catch (Exception e){
            String jsonStr = JSONUtil.toJsonStr(new ResultBean(500, "无权限", null));
            servletResponse.getWriter().write(jsonStr);
        }

    }

    public static void main(String[] args) {

        String str = "hanchun123";
        String s = DigestUtil.md5Hex(str);
        System.out.println(s);
    }
}
